package admin

import (
	"encoding/json"
	"fmt"
	"go_auth/ext/settings"
	"go_auth/utils/commons"
	"go_auth/utils/mysql"
)

type AdInfo struct {
	Id     int64
	Url    string //图片url
	Name   string //名称
	Period int    `xorm:"int(4) 'period' default 3 "`  //间隔时间
	Rank   int    `json:"Rank"`                        //排序
	Status int    `xorm:"int(4) 'status' default -1 "` //是否显示 1显示，-1不显示
}

func (ad *AdInfo) AddAdInfo() int64 {

	insert, err := settings.MasterDB.Insert(ad)
	if commons.CheckErr(err) {
		return insert
	}
	return settings.Zero
}

func GetAllAd() []byte {

	ad := make([]AdInfo, 0)

	find := settings.MasterDB.Where("status=?", true).Desc("rank").Find(&ad)
	if !commons.CheckErr(find) {
		return nil
	}
	marshal, err := json.Marshal(&ad)
	if commons.CheckErr(err) {
		return marshal
	}

	return nil
}

func UpdateAd(b []byte) bool {

	s := settings.MasterDB.NewSession()

	var err error
	if err = s.Begin(); err != nil {
		return false
	}
	var ad []AdInfo
	fmt.Println(string(b))
	err = json.Unmarshal(b, &ad)
	if !commons.CheckErr(err) {
		return false
	}

	defer s.Rollback()
	for _, v := range ad {
		if !(mysql.CheckErrUpdate(s, v, v.Id)) {
			return false
		}
	}
	s.Commit()
	s.Close()
	return true

}
